﻿using PromoOffersCrawler.Crawler.Managers;
using PromoOffersCrawler.Web.Managers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace PromoOffersCrawler.Web.Controllers
{
    public class CrawlerController : Controller
    {
        //
        // GET: /Crawler/

        public ActionResult StartCrawl(int webSiteID)
        {
            var webSite = new PromoOffersCrawler.Crawler.Data.Entities().WebSites.First(x => x.ID == webSiteID);

            var crawler = new WebSiteCrawler(webSite);

            //return Json(new { Progress = 0, siteID = webSiteID, OpperationID = Managers.CrawlerManager.RegisterOperation(crawler) }, JsonRequestBehavior.AllowGet);
            int opperationID = Managers.CrawlerManager.RegisterOperation(crawler);
            Task.Run(() => crawler.Crawl());

            return RedirectToAction("CrawlDetails", new { opperationId = opperationID });
        }

        public ActionResult CrawlDetails(int opperationId)
        {
            var messages = CrawlerManager.GetMessages(opperationId);

            return View(messages);
        }

        public JsonResult GetProgress(int operationID, int siteID)
        {
            return Json(new { Progress = Managers.CrawlerManager.GetProgres(operationID), siteID = siteID, OpperationID = operationID }, JsonRequestBehavior.AllowGet);
        }

    }
}
